<?php

namespace Yjius\common;

class CurlHelper
{
    /**
     * Purpose: httpRequest
     * $url : curl请求连接
     * $headers：头部信息
     * $method ： 请求方式
     * $params：传递参数（一般拼接在链接上）
     * $data：postdata参数
     * $timeout 10s
     *
     * 来自各项目common/function  httpRequest方法
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/2/24 10:28
     */
    static function httpRequest($url, $headers = [], $method = 'GET', $params = null, $data = [], $timeout = 10)
    {
        $method = strtoupper($method);
        $requestString = "";
        if (is_array($params)) {
            if ($method == 'GET' || $method == 'POST') {
                $requestString = http_build_query($params);
                if (strpos($url, '?') !== false) {
                    $url .= "&" . $requestString;
                } else {
                    $url .= "?" . $requestString;
                }
            }
        } else {
            $requestString = $params ?: '';
        }

        if (in_array($method, ['POST', 'PUT']) && is_array($data)) {
            $data = http_build_query($data);
        }
        // setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Chrome 42.0.2311.135');
        // setting the POST FIELD to curl
        switch ($method) {
            case "GET" :
                curl_setopt($ch, CURLOPT_HTTPGET, 1);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case "PUT" :
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
                break;
            default:
                curl_close($ch);
                throw new \Exception("error request method type!");
                break;
        }
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $errno = curl_errno($ch);
        if ($errno && $httpCode != '200') {
            curl_close($ch);
            throw new \Exception('Curl error: (' . $errno . ')' . curl_error($ch));
        }
        curl_close($ch);
        return $response;
    }

}
